package com.bestcem.xm.txtanls.controller;

import cn.hutool.core.lang.Validator;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.txtanls.controller.param.chart.BaseChartQuery;
import com.bestcem.xm.txtanls.controller.param.chart.ChartValid;
import com.bestcem.xm.txtanls.controller.vo.DownloadRecordVO;
import com.bestcem.xm.txtanls.controller.vo.PageResponseVO;
import com.bestcem.xm.txtanls.controller.vo.RecordInfoVO;
import com.bestcem.xm.txtanls.enums.PeriodTypeEnum;
import com.bestcem.xm.txtanls.grpc.service.param.PageParam;
import com.bestcem.xm.txtanls.grpc.service.param.chart.BaseChartParam;
import com.bestcem.xm.txtanls.grpc.service.param.record.DownloadRecordParam;
import com.bestcem.xm.txtanls.grpc.service.param.record.ListRecordParam;
import com.bestcem.xm.txtanls.grpc.service.param.record.QueryConditionParam;
import com.bestcem.xm.txtanls.grpc.service.param.record.RecordTopicRelationParam;
import com.bestcem.xm.txtanls.service.RecordService;
import com.bestcem.xm.txtanls.service.dto.PageResultDTO;
import com.bestcem.xm.txtanls.service.dto.chart.PeriodTimeDTO;
import com.bestcem.xm.txtanls.service.dto.chart.TimeRangeDTO;
import com.bestcem.xm.txtanls.service.dto.record.ListRecordDTO;
import com.bestcem.xm.txtanls.service.dto.record.RecordTopicRelationDTO;
import com.bestcem.xm.txtanls.util.ChartUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.bestcem.xm.txtanls.controller.convert.RecordConvert.listRecordTransfer;

/**
 * @author gy.liu
 * @version 2.0
 * @date 2021/8/5 14:42
 **/
@Api(tags = "原话记录相关接口")
@RestController
@RequestMapping(value = "/txtanls", produces = MediaType.APPLICATION_JSON_VALUE)
public class RecordController {

    private final static Logger LOGGER = LoggerFactory.getLogger(RecordController.class);
    @Resource
    RecordService recordService;

    /**
     * 根据输入词查询原话记录
     *
     * @param projectId
     * @param fieldId
     * @param filterType
     * @param current
     * @param startTime
     * @param endTime
     * @param page
     * @param emotion
     * @param topicId
     * @param word
     * @return XmResultJson
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/12
     */
    @ApiOperation(value = "根据输入词查询原话记录")
    @GetMapping(value = "/record/search")
    public XmResultJson<PageResponseVO<List<RecordInfoVO>>> listRecord(@RequestParam(value = "project_id") String projectId,
                                                                       @RequestParam(value = "field_id", required = false) String fieldId,
                                                                       @RequestParam(value = "dtfiltertype", required = false) String filterType,
                                                                       @RequestParam(value = "current", required = false) String current,
                                                                       @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                                                       @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                                                                       @RequestParam(value = "page") Integer page,
                                                                       @RequestParam(value = "data_use") Integer dataUse,
                                                                       @RequestParam(value = "period", required = false) Integer period,
                                                                       @RequestParam(value = "emotion", required = false) Integer emotion,
                                                                       @RequestParam(value = "topicId", required = false) String topicId,
                                                                       @RequestParam(value = "input_word", required = false) String word,
                                                                       @RequestParam(value = "rowsPerPage", required = false) Integer rowsPerPage,
                                                                       @RequestParam(value = "viewpoint_id", required = false) String viewpointId) {
        ListRecordParam listRecordParam = null;
        TimeRangeDTO timeRangeDTO = null;
        if (page > 0) {
            page--;
        }
        PageParam pageParam = new PageParam(page, Objects.isNull(rowsPerPage) ? 20 : rowsPerPage);
        // 组装查询参数
        QueryConditionParam queryConditionParam = new QueryConditionParam();
        queryConditionParam.setEmotion(emotion);
        queryConditionParam.setFieldId(fieldId);
        queryConditionParam.setProjectId(projectId);
        queryConditionParam.setTopicId(topicId);
        queryConditionParam.setWord(word);
        queryConditionParam.setDataUse(dataUse);
        queryConditionParam.setViewpointId(viewpointId);

        if (StringUtils.isNotEmpty(filterType)) {
            BaseChartQuery baseChartQuery = new BaseChartQuery(projectId, fieldId, filterType, current, startTime, endTime);
            BaseChartParam baseChartParam = baseChartQuery.getBaseChartParam();
            String errorMessage = ChartValid.validBaseChartParam(baseChartParam);
            if (Validator.isNotNull(errorMessage)) {
                return XmResultJson.fail(5, errorMessage);
            }
            timeRangeDTO = baseChartParam.getTimeRangeDTO();
            if(Validator.isNotNull(period) && period == PeriodTypeEnum.LAST.getIndex()) {
                PeriodTimeDTO lastPeriodTime = ChartUtil.getLastPeriodTime(timeRangeDTO);
                timeRangeDTO.setPeriodTime(lastPeriodTime);
            }
        } else {
            timeRangeDTO = new TimeRangeDTO();
        }

        listRecordParam = new ListRecordParam(pageParam, timeRangeDTO, queryConditionParam);
        ServiceResult<ListRecordDTO> serviceResult = recordService.listRecord(listRecordParam);
        if (Objects.isNull(serviceResult)) {
            return XmResultJson.fail(5, "根据输入词查询原话记录失败");
        }
        if (!serviceResult.isSuccess()) {
            return XmResultJson.fail(5, serviceResult.getMsg());
        }
        ListRecordDTO data = serviceResult.getData();
        PageResultDTO pageResultDTO = new PageResultDTO();
        pageResultDTO.setTotal(data.getPageResult().getTotal());
        pageResultDTO.setData(listRecordTransfer(data.getPageResult().getData()));

        return XmResultJson.success(new PageResponseVO<>(pageParam, pageResultDTO, ""));
    }


    /**
     * 导出原话记录
     *
     * @param projectId
     * @param fieldId
     * @param filterType
     * @param current
     * @param startTime
     * @param endTime
     * @param dataUse
     * @param emotion
     * @param topicId
     * @param word
     * @return XmResultJson
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/12
     */
    @ApiOperation(value = "导出原话记录")
    @GetMapping(value = "/record/download")
    public XmResultJson<DownloadRecordVO> downloadRecord(@RequestParam(value = "project_id") String projectId,
                                                         @RequestParam(value = "field_id", required = false) String fieldId,
                                                         @RequestParam(value = "dtfiltertype", required = false) String filterType,
                                                         @RequestParam(value = "current", required = false) String current,
                                                         @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                                         @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                                                         @RequestParam(value = "data_use") Integer dataUse,
                                                         @RequestParam(value = "page",required = false) Integer page,
                                                         @RequestParam(value = "period", required = false) Integer period,
                                                         @RequestParam(value = "emotion", required = false) Integer emotion,
                                                         @RequestParam(value = "topicId", required = false) String topicId,
                                                         @RequestParam(value = "input_word", required = false) String word,
                                                         @RequestParam(value = "rowsPerPage", required = false) Integer rowsPerPage,
                                                         @RequestParam(value = "viewpoint_id", required = false) String viewpointId,
                                                         HttpServletResponse response) {

        TimeRangeDTO timeRangeDTO = null;

        // 组装查询参数
        QueryConditionParam queryConditionParam = new QueryConditionParam();
        queryConditionParam.setProjectId(projectId);
        queryConditionParam.setWord(word);
        queryConditionParam.setTopicId(topicId);
        queryConditionParam.setFieldId(fieldId);
        queryConditionParam.setEmotion(emotion);
        queryConditionParam.setDataUse(dataUse);
        queryConditionParam.setViewpointId(viewpointId);
        if (StringUtils.isNotEmpty(filterType)) {
            BaseChartQuery baseChartQuery = new BaseChartQuery(projectId, fieldId, filterType, current, startTime, endTime);
            BaseChartParam baseChartParam = baseChartQuery.getBaseChartParam();
            String errorMessage = ChartValid.validBaseChartParam(baseChartParam);
            if (Validator.isNotNull(errorMessage)) {
                return XmResultJson.fail(5, errorMessage);
            }
            timeRangeDTO = baseChartParam.getTimeRangeDTO();
            if(Validator.isNotNull(period) && period == PeriodTypeEnum.LAST.getIndex()) {
                PeriodTimeDTO lastPeriodTime = ChartUtil.getLastPeriodTime(timeRangeDTO);
                timeRangeDTO.setPeriodTime(lastPeriodTime);
            }
        } else {
            timeRangeDTO = new TimeRangeDTO();
        }

        DownloadRecordParam downloadRecordParam = new DownloadRecordParam();
        downloadRecordParam.setQueryParam(queryConditionParam);
        downloadRecordParam.setTimeRangeDTO(timeRangeDTO);
        ServiceResult<DownloadRecordVO> serviceResult = recordService.downloadRecordForHttp(downloadRecordParam);
        if (Objects.isNull(serviceResult)) {
            return XmResultJson.fail(5, "导出原话记录失败");
        }
        if (!serviceResult.isSuccess()) {
            return XmResultJson.fail(5, serviceResult.getMsg());
        }
        return XmResultJson.success(serviceResult.getData());
    }

    /**
     * 话题关联原话记录的数量
     *
     * @param projectId
     * @return RecordTopicRelationDTO
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/5
     */
    @ApiOperation(value = "话题关联原话记录的数量")
    @GetMapping(value = "/record/relation/info")
    public XmResultJson<RecordTopicRelationDTO> getRecordTopicRelation(@RequestParam(value = "projectid") String projectId) {
        RecordTopicRelationParam recordTopicRelationParam = new RecordTopicRelationParam();
        recordTopicRelationParam.setTimeRangeDTO(new TimeRangeDTO());
        recordTopicRelationParam.setProjectId(projectId);
        ServiceResult<RecordTopicRelationDTO> serviceResult = recordService.getRecordTopicRelation(recordTopicRelationParam);
        if (Objects.isNull(serviceResult)) {
            return XmResultJson.fail(5, "获取话题关联原话记录的数量失败");
        }
        if (!serviceResult.isSuccess()) {
            return XmResultJson.fail(5, serviceResult.getMsg());
        }
        return XmResultJson.success(serviceResult.getData());
    }


    @ApiOperation(value = "获取原话记录中的最大时间")
    @GetMapping(value = "/time/max/{id}")
    public XmResultJson<String> getRecordMaxTime(@ApiParam(value = "项目id", required = true)
                                                 @PathVariable(value = "id") String id) {
        ServiceResult<LocalDateTime> recordMaxTime = recordService.getRecordMaxTime(id);
        if (recordMaxTime.isSuccess()) {
            return XmResultJson.success(recordMaxTime.getData().toLocalDate().toString());
        } else {
            return XmResultJson.fail(5, "获取原话记录中的最大时间失败");
        }
    }

}
